 <template>
  <div class="page">
    <s-header :name="'竣工验收办理'" :back="'/government/finish-work'"></s-header>
    <div class="card-box">
      <div class="card-item">
        <div class="card-header">
          <div class="header-title item-head">
            <div class="title">竣工申请信息</div>
            <span class="notice-status" @click="goToDetail(buildDataForm.id)">建房申请详情</span>
          </div>
        </div>
        <van-divider />
        <div class="card-body card-body-nop">
          <van-cell title="申请人" :value="buildDataForm.applyName" />
          <van-cell title="申请时间" :value="buildDataForm.applyTime" />
          <van-cell title="申请内容" :value="buildCompletedApply.applyContent" />
          <van-cell title="现场图片" value="" />
          <div class="img-box">
            <van-image
              v-for="(item, index) in buildCompletedApply.photos"
              :key="index"
              :src="item.url"
              class="pictures"
              @click="handleReview(item.url)"
            />
          </div>
          <van-cell title="相关材料" value="" />
          <div v-for="(item, index) in buildCompletedApply.files" :key="index" class="file-box">
            <div class="file-item" @click="handleDownload(item.url, item.suffix)">
              {{ item.name }}
              <span class="size" v-if="item.size">（{{ item.size }}）</span>
            </div>
          </div>
        </div>
      </div>

      <div class="card-item">
        <div class="card-header">
          <div class="item-head">
            <div class="title title-required">审查项</div>
            <div class="text-add" @click="handleToEdit(null, 'add')">新增</div>
          </div>
        </div>
        <van-divider />
        <div class="card-body">
          <div class="item-body">
            <van-cell
              v-for="item in reviewItems"
              :key="item.itemId"
              :title="item.itemName"
              is-link
              @click="handleToEdit(item.reviewItemId, 'edit')"
            />
          </div>
        </div>
      </div>

      <van-form ref="dataFormRef">
        <div class="card-item">
          <div class="card-header">
            <div class="header-title title-required">验收意见</div>
          </div>
          <van-divider />
          <div class="card-body">
            <van-radio-group v-model="dataForm.completedResult" :rules="dataRule.completedResult" direction="horizontal">
              <van-radio name="42">通过</van-radio>
              <van-radio name="43">退回给申请人</van-radio>
              <van-radio name="99">挂起</van-radio>
            </van-radio-group>
          </div>
        </div>

        <div class="card-item">
          <div class="card-header">
            <div class="header-title title-required">办理意见</div>
          </div>
          <van-divider />
          <div class="card-body">
            <van-field
              v-model="dataForm.handleOpinions"
              :rules="dataRule.handleOpinions"
              class="noPadding"
              label=""
              rows="3"
              autosize
              type="textarea"
              placeholder="请输入办理意见"
            />
          </div>
        </div>
      </van-form>

      <div class="card-item last-item">
        <div class="card-header">
          <div class="item-head">
            <div class="title title-required">相关材料</div>
            <div class="text-desc">（请上传农村宅基地和建房验收意见）</div>
          </div>
        </div>
        <van-divider />
        <div class="card-body">
          <image-upload v-model:value="otherFileList" fileType="A20" @uploadBack="uploadBack"></image-upload>
        </div>
      </div>
    </div>

    <div class="btn-group">
      <van-button type="button" class="cus-btn btn-default" @click="handleSave">保存</van-button>
      <van-button :loading="isCommit" type="button" class="cus-btn btn-primary" @click="handleTransact">提交</van-button>
    </div>
  </div>
</template>

<script>
import { reactive, toRefs, ref, onMounted, getCurrentInstance, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
import { Toast, ImagePreview } from 'vant'
import sHeader from '@/components/SimpleHeader'
import ImageUpload from '@/components/ImageUpload'
import { getCompletedDetail, saveCompleted } from '@/service/govern'
export default {
  components: { sHeader, ImageUpload },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const store = useStore()
    const dataFormRef = ref(null)
    const state = reactive({
      isCommit: false,
      dataForm: {
        id: '',
        completedResult: '42',
        handleOpinions: '',
      },
      buildDataForm: {
        id: '',
        applyOrderNo: '',
        applyName: '',
        applyTime: '',
        applyPhone: '',
        applyReasonsDesc: '',
        buildTypeName: '',
        applyHouseAddress: '',
      },
      buildCompletedApply: {
        applyContent: '',
        files: [],
        photos: [],
      },
      completedApplyId: '',
      finishId: '',
      reviewItems: [],
      otherFileList: [],
      attachInfoList: [],
      pdfSrc: '', // pdf文件地址
      numPages: undefined,
      dataRule: {
        handleOpinions: [{ required: true, message: '请输入办理意见', trigger: 'onBlur' }],
        completedResult: [{ required: true, message: '请选择验收意见', trigger: 'onChange' }],
      },
    })

    // 全局属性
    const { listAssign, converSize } = getCurrentInstance().appContext.config.globalProperties
    store.dispatch('getFileServerPrefix')

    onMounted(async () => {
      const { id } = route.params
      if (id && id != 'undefined') {
        getCompletedDetail(id).then((res) => {
          const data = res.data
          state.reviewItems = data.reviewItemDTOS || []

          listAssign(state.buildDataForm, data.buildApplyBase)
          listAssign(state.buildCompletedApply, data.buildCompletedApply)
          state.completedApplyId = data.buildCompletedApply.id
          state.finishId = data.buildCompletedOpinions.id
          if (data.buildCompletedOpinions) {
            listAssign(state.dataForm, data.buildCompletedOpinions)
            // state.attachInfoList = [...data.buildCompletedOpinions.files]

            let otherFileList = data.buildCompletedOpinions.files
            if (otherFileList && otherFileList.length > 0) {
              otherFileList.forEach((item) => {
                if (item.url.indexOf(fileServerPrefix.value) === -1) {
                  item.filePath = item.url
                  item.url = fileServerPrefix.value + item.url
                }
              })
            }
            state.otherFileList = otherFileList
          }

          state.buildCompletedApply.photos.forEach((item) => {
            item.url = fileServerPrefix.value + item.url
            item.size = converSize(item.size)
          })
          state.buildCompletedApply.files.forEach((item) => {
            item.url = fileServerPrefix.value + item.url
            item.size = converSize(item.size)
          })
        })
      } else {
        router.push({ path: `/government/finish-work` })
      }
    })

    const handleToEdit = (id, type) => {
      sendRequest(false).then(() => {
        router.push({
          path: '/government/review-item',
          query: {
            id: id,
            type: type,
            pageId: route.params.id,
            applyBaseId: state.buildDataForm.id,
            reviewModule: '10',
            deptCode: '005',
            pagePath: '/government/finish-work/transact',
          },
        })
      })
    }

    // 文件上传后回调
    const uploadBack = (fileList) => {
      state.otherFileList = fileList
    }

    const handleReview = (url) => {
      ImagePreview({
        images: [url],
        showIndex: true,
        showIndicators: true,
        closeable: true,
      })
    }

    const handleDownload = (url, suffix) => {
      if (suffix === 'png' || suffix === 'jpg' || suffix === 'jpeg') {
        ImagePreview({
          images: [url],
          showIndex: true,
          showIndicators: true,
          closeable: true,
        })
      } else if (suffix === 'pdf') {
        window.open(url)
      } else {
        let a = document.createElement('a')
        a.href = url
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
      }
    }

    const handleSave = () => {
      sendRequest(false).then(() => {
        Toast.success('保存成功')
        setTimeout(() => {
          router.push({ path: `/government/finish-work` })
        }, 500)
      })
    }

    const goToDetail = (id) => {
      if (id) {
        router.push({ path: `/government/build-apply/detail/${id}` })
      }
    }

    const handleTransact = () => {
      dataFormRef.value.validate().then(() => {
        if (state.reviewItems.length === 0) {
          Toast.fail('请新增审查项')
          return
        }
        if (state.otherFileList.length === 0) {
          Toast.fail('请上传相关材料')
          return
        }
        sendRequest(true).then(() => {
          Toast.success('提交成功')
          setTimeout(() => {
            router.push({ path: `/government/finish-work` })
          }, 500)
        })
      })
    }

    const sendRequest = (isSubmit) => {
      return new Promise((resolve, reject) => {
        let otherFileList = JSON.parse(JSON.stringify(state.otherFileList))
        otherFileList.forEach((item, index) => {
          item.sort = index
          item.url = item.filePath ? item.filePath : item.url
        })

        state.isCommit = true
        let params = state.dataForm
        params.attachInfoList = otherFileList
        params.completedApplyId = state.completedApplyId
        params.id = state.finishId
        params.isSubmit = isSubmit
        saveCompleted(params)
          .then(() => {
            state.isCommit = false
            resolve(true)
          })
          .catch((err) => {
            state.isCommit = false
            reject(err)
          })
      })
    }

    const fileServerPrefix = computed(() => {
      return store.state.fileServerPrefix
    })

    return {
      dataFormRef,
      fileServerPrefix,
      ...toRefs(state),
      handleTransact,
      handleSave,
      handleToEdit,
      goToDetail,
      handleReview,
      handleDownload,
      uploadBack,
    }
  },
}
</script>

<style lang="less" scoped>
@import '@/common/style/mixin';
.page {
  color: #2e3f6a;
  font-weight: 400;
  .card-box {
    margin-top: 10px;
    .van-divider {
      margin: 10px 0 0;
    }
    .card-header {
      font-size: 15px;
      .item-head {
        .fj();
        .text-add {
          font-weight: 400;
          color: #3487f6;
        }
        .text-desc {
          font-size: 13px;
          font-weight: 400;
          color: #9297ae;
        }
        .notice-status {
          font-size: 12px;
          font-weight: 400;
          background: #3487f6;
          border-radius: 3px;
          color: #ffffff;
          padding: 4px 14px;
        }
      }
      .title-required::before {
        margin-right: 5px;
        color: var(--van-field-required-mark-color);
        content: '*';
      }
    }
    .card-body {
      padding-bottom: 10px;
      .person {
        margin-bottom: 10px;
        padding-bottom: 10px;
      }
      .img-box {
        padding: 10px 14px 0;
        .pictures {
          width: 53px;
          height: 53px;
          margin-right: 10px;
        }
      }
      .file-box {
        padding: 10px 14px 0;
        .file-item {
          font-size: 13px;
          font-weight: 400;
          color: #3487f6;
          margin-bottom: 6px;
          .size {
            color: #9297ae;
          }
        }
      }
    }
    .last-item {
      margin-bottom: 0;
    }
  }
  .btn-group {
    padding: 30px 0 20px;
    .cus-btn {
      width: 167px;
    }
  }
}
</style>
